<?php
declare (strict_types=1);

namespace app\backend\controller\v1;

use think\Request;

class Upload extends BaseController
{
    /**
     * 单图上传
     *
     * @return \think\Response
     */
    public function image()
    {
        // 获取表单上传文件
        $file = request()->file('image');
        if (empty($file)) return errMsg(400, '请选择要上传图片！');
        try {
            //  验证图片规则
            validate(['image' => 'filesize:2048000|fileExt:jpg,jpeg,png'])
                ->check(['image' => $file]);
            //  图片保存位置
            $savename = \think\facade\Filesystem::disk('public')->putFile('backendUploads', $file);
            return sucessMsg(200, '上传成功！', $savename);
        } catch (\think\exception\ValidateException $e) {
            return errMsg(422, $e->getMessage());
        }
    }

    /**
     * 多图上传
     *
     * @return \think\Response
     */
    public function images()
    {
        // 获取表单上传文件
        $files = request()->file('images');
        if (empty($files)) return errMsg(400, '请选择要上传图片！');
        try {
            validate(['image'=>'filesize:2048000|fileExt:jpg,jpeg,png'])
                ->check($files);
            //  图片保存位置
            $savename = [];
            foreach($files as $file) {
                $savename[] = \think\facade\Filesystem::disk('public')->putFile('backendUploads', $file);
            }
            return sucessMsg(200, '上传成功！', $savename);
        } catch (\think\exception\ValidateException $e) {
            return errMsg(422, $e->getMessage());
        }
    }

}
